package com.example.actionsignin.dialog;

import android.Manifest;
import android.app.DialogFragment;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.example.actionsignin.R;
import com.example.actionsignin.entity.LoginEntity;
import com.example.actionsignin.http.HttpUtil;
import com.example.actionsignin.utils.FingerprintUtil;
import com.example.actionsignin.utils.PermissionUtil;
import com.example.actionsignin.utils.ShakeUtil;
import com.example.actionsignin.utils.ToastUtil;
import com.example.actionsignin.utils.VoiceUtil;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static android.content.ContentValues.TAG;

/**
 * Created by 旭 on 2017/10/6/006.
 */

public class SignDialogFragment extends DialogFragment implements
        VoiceUtil.OnVoiceListener,
        FingerprintUtil.OnFingerprintListener,
        View.OnClickListener,
        ShakeUtil.OnShakeListener{

    private View view;
    private ImageView imageView;
    private TextView textView;
    private int mType;
    private String mAid;

    //摇一摇
    private ShakeUtil mShakeUtil;
    private int number_shake = 0;

    //定位
    private LatLng myLatLng;
    private LatLng targetLatLng;
    AMapLocationClient mapLocationClient = null;
    AMapLocationListener locationListener = null;
    AMapLocationClientOption locationClientOption = null;

    //语音识别
    private VoiceUtil mVoiceUtil;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(STYLE_NO_TITLE);

        view = inflater.inflate(R.layout.fragment_dialog_sign,container,false);

        initView();

        mType = getArguments().getInt("type");
        mAid = getArguments().getString("aid");
        initData();

        return view;
    }

    private void initData()
    {
        switch (mType)
        {
            //人脸识别
            case 0:
                break;
            //语音识别
            case 1:
                imageView.setImageResource(R.mipmap.sign_type_4);
                textView.setText("请进行语音识别");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                {
                    if (PermissionUtil.isPermissions(getActivity(),Manifest.permission.RECORD_AUDIO,1))
                    {
                        mVoiceUtil = new VoiceUtil(getActivity());
                        mVoiceUtil.setVoiceListener(this);
                    }else {
                        ToastUtil.INSTANCE(getActivity(),"无权限");
                    }
                }else {
                    mVoiceUtil = new VoiceUtil(getActivity());
                    mVoiceUtil.setVoiceListener(this);
                }

                break;
            //指纹识别
            case 2:
                imageView.setImageResource(R.mipmap.sign_type_3);
                textView.setText("请进行指纹识别");
                FingerprintUtil fingerprintUtil = new FingerprintUtil(getActivity());
                fingerprintUtil.doFingerPrint();
                fingerprintUtil.setFingerprintListener(this);
                break;
            //GPS定位
            case 3:
                imageView.setImageResource(R.mipmap.sign_type_2);
                textView.setText("点击定位进行签到");
                double x = getArguments().getDouble("x");
                double y = getArguments().getDouble("y");
                targetLatLng = new LatLng(x,y);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                {
                    if (PermissionUtil.isPermissions(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION,0))
                    {
                        doLocation();
                    }else {
                        ToastUtil.INSTANCE(getActivity(),"无权限");
                    }
                }else {
                    doLocation();
                }

                break;
            //摇一摇
            case 4:
                imageView.setImageResource(R.mipmap.sign_type_1);
                textView.setText("摇晃手机进行签到");
                mShakeUtil = new ShakeUtil(getActivity());
                mShakeUtil.setOnShakeListener(this);
                break;
        }
    }

    private void initView() {
        textView = (TextView) view.findViewById(R.id.fragment_dialog_text);
        imageView = (ImageView) view.findViewById(R.id.fragment_dialog_image);
        imageView.setOnClickListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        getDialog().getWindow().setLayout((int) (displayMetrics.widthPixels * 0.9f),getDialog().getWindow().getAttributes().height);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mShakeUtil != null)
        {
            mShakeUtil.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mShakeUtil != null)
        {
            mShakeUtil.onPause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapLocationClient != null)
        {
            mapLocationClient.onDestroy();
        }
        if (mVoiceUtil != null)
        {
            mVoiceUtil.stopVoice();
        }
    }

    @Override
    public void onShake() {
        ++number_shake;
        Log.d(TAG, "onShake: " + number_shake);
        if (number_shake == 3)
        {
            sendSign();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.fragment_dialog_image:
                selectOnClick();
                break;
        }
    }

    private void selectOnClick() {
        switch (mType)
        {
            case 1:
                mVoiceUtil.startVoice();
                break;
            case 3:
                if (targetLatLng != null && myLatLng != null)
                {
                    float distance = AMapUtils.calculateLineDistance(targetLatLng,myLatLng);
                    Log.d(TAG, "selectOnClick: " + distance);
                    if (distance > 300)
                    {
                        ToastUtil.INSTANCE(getActivity(),"太远了(〒︿〒)");
                    }else {
                        sendSign();
                        ToastUtil.INSTANCE(getActivity(),"签到成功");
                    }
                }
                break;
        }
    }

    private void doLocation()
    {
        mapLocationClient = new AMapLocationClient(getActivity());

        locationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation !=  null)
                {
                    if (aMapLocation.getErrorCode() == 0)
                    {
                        ToastUtil.INSTANCE(getActivity(),"定位成功");
                        String address = aMapLocation.getAddress();
                        double latitude = aMapLocation.getLatitude();
                        double longitude = aMapLocation.getLongitude();
                        Log.d("TAGG","address = " + address);
                        Log.d("TAGG","latitude = " + latitude);
                        Log.d("TAGG","longitude = " + longitude);

                        myLatLng = new LatLng(latitude,longitude);

                    }else {
                        ToastUtil.INSTANCE(getActivity(),"定位失败");
                    }
                }
            }
        };

        mapLocationClient.setLocationListener(locationListener);

        locationClientOption = new AMapLocationClientOption();
        locationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationClientOption.setOnceLocation(true);
        locationClientOption.setOnceLocationLatest(true);
        locationClientOption.setNeedAddress(true);
        locationClientOption.setHttpTimeOut(10 * 1000);
        locationClientOption.setMockEnable(true);
        locationClientOption.setLocationCacheEnable(false);

        mapLocationClient.setLocationOption(locationClientOption);
        mapLocationClient.startLocation();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode)
        {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    doLocation();
                }else {
                    ToastUtil.INSTANCE(getActivity(),"无权限");
                }
                break;
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    mVoiceUtil = new VoiceUtil(getActivity());
                    mVoiceUtil.setVoiceListener(this);
                }else {
                    ToastUtil.INSTANCE(getActivity(),"无权限");
                }

                break;
        }
    }

    private void sendSign() {
        HttpUtil.onSend().onSignAction(mAid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginEntity>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull LoginEntity loginEntity) {
                        if (loginEntity.getResult().equals("1"))
                        {
                            ToastUtil.INSTANCE(getActivity(),"签到成功");
                        }else {
                            ToastUtil.INSTANCE(getActivity(),"已签到");
                        }
                        dismiss();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        Log.d(TAG, "onError: " + e);
                        ToastUtil.INSTANCE(getActivity(),"请打开网络！");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onFingerprint() {
        sendSign();
    }

    @Override
    public void onVoice() {
        sendSign();
    }
}
